package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pojo.Customer;
import service.CustomerManager;
import service.impl.CustomerManagerFactory;

/**
 * Servlet implementation class AddCustomerServlet
 */
public class AddCustomerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private CustomerManager manager;
    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddCustomerServlet() {
        super();
        manager=CustomerManagerFactory.getInstance();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");                      //解决中文乱码
		response.setHeader("content-type","text/html;charset=UTF-8");//解决中文乱码
		StringBuilder errorInfo=new StringBuilder("数据输入错误!</br>");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		boolean isLegal = true; 
		//接参
		String cname = request.getParameter("cname");
		String csex = request.getParameter("sex");
		String csal = request.getParameter("sal");
		String cbirth = request.getParameter("birth");
		String[] cfavs = request.getParameterValues("favs");
		

		Date birth =null;
		boolean sex=false;
		double sal=0;
		//校验
		if("".equals(cname)||"".equals(csex)||"".equals(csal)||"".equals(cbirth)){
			errorInfo.append("数据不能为空!</br>");
			isLegal=false;
		}
		else{
			//类型转换
			try {
				birth = (Date)sdf.parse(cbirth);
				sex = Boolean.parseBoolean(csex);
				sal = Double.parseDouble(csal);
			} catch (ParseException e) {
				errorInfo.append("数据输入不合法!</br>");
				birth = null;
				isLegal=false;
				e.printStackTrace();
			}
		}
		
		
		//封装
		Customer c = new Customer(null, cname, sal, sex, birth, cfavs);
		
		//业务
		if(isLegal){
			//转发
			int m = manager.addCustomer(c);
			PrintWriter out = response.getWriter();
			response.sendRedirect("List");
		}
		else{
			PrintWriter out = response.getWriter();
			out.print(errorInfo.toString());
			out.close();
		}
	}

}
